package com.vickcan.vdp.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.GroupedMap;
import cn.hutool.setting.Setting;
import com.vickcan.vdp.domain.VConfig;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: ByteExpress
 * @Date: 2024/8/28 22:33
 * @Version V1.0
 */
@Component
public class CfgFactory implements InitializingBean {
    private Map<String, VConfig> configMap = new ConcurrentHashMap<>();

    @Value("${configDir}")
    private String configDir;

    public VConfig getById(String id){
        return configMap.get(id);
    }

    @Override
    public void afterPropertiesSet() {
        for (String fileName : FileUtil.listFileNames(configDir)) {
            Setting setting = new Setting(FileUtil.touch(configDir + File.separator + fileName), CharsetUtil.CHARSET_UTF_8, true);
            GroupedMap groupedMap = setting.getGroupedMap();
            configMap.put(fileName.substring(0, fileName.indexOf(".")), JSONUtil.toBean(JSONUtil.toJsonStr(groupedMap), VConfig.class));
            System.out.println();
        }
    }
}
